package com.financing.platform.web.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.financing.platform.dao.IProjectDao;
import com.financing.platform.dto.FpNewProductDTO;
import com.financing.platform.dto.FpRelevanceDTO;
import com.financing.platform.dto.ProjectDTO;
import com.financing.platform.service.IFpNewProductService;
import com.financing.platform.service.IFpRelevanceService;
import com.financing.platform.service.IfpFetchProductRegexService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.YicaifuWbClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

/**
 * 
 * @ClassName: yCFProductInfoJob
 * @Description:壹财富产品
 *
 */
@Controller("yCFProductInfoAction")
@RequestMapping("/api/yCFProductInfo")
@Scope("prototype")
public class YCFProductInfoAction {
	
	private Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	private IFpNewProductService fpNewProductService;
	
	@Autowired
	private IFpRelevanceService fpRelevanceService;
	
	@Autowired
	private IfpFetchProductRegexService fpFetchProductRegexService;
	
	@Autowired
	private IProjectDao projectDao;
	/***
	 * 
	
	* @Title: YCFProductInfoJob
	
	* @Description:测试   接口调用
	
	* @param @param request
	* @param @param response
	* @param @throws Exception    设定文件
	
	* @return void    返回类型
	
	* @throws
	 */
	@RequestMapping("/ycfProductInfoJob.shtml")
	public void YCFProductInfoJob(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		try {
			//切换IP   切换3次
//			boolean memcache = YicaifuWbClient.getMemcache();
			
			log.info("auto YCFProductInfoJob info .....");
			//壹财富登录   账号  随机切换
//			YicaifuWbClient.LoginYCF("18016325069","2af9b1ba42dc5eb01743e6b3759b6e4b");
			//赋值cookie 
//			YicaifuWbClient.httpToWebClient();
			//壹财富数据      预售和在售
//			String ycfTrustUrl="https://www.1caifu.com/trust/2/?&ag=1&_="+System.currentTimeMillis();
			String ycfTrustUrl="http://1caifu.com/trust/1/?id=1&productTypeId=1&issaleses=10,20&sortBy=0&ag=1&_="+System.currentTimeMillis();
			//壹财富数据      预售和在售
			String ycfassetManagementUrl="http://1caifu.com/asset-management/1/?id=1&productTypeId=2&issaleses=10,20&sortBy=0&ag=1&_="+System.currentTimeMillis();
			
			//壹财富数据  债权  预售和在售
//			String ycfobligationfundUrl="http://1caifu.com/obligation-fund";
			
			String urlDetailRegex="/.+_.+\\.html";
			//获取到所有的详情页地址
			List<HtmlAnchor> trustList=YicaifuWbClient.getListUrl(ycfTrustUrl,urlDetailRegex);
			List<HtmlAnchor> assetManagementList=YicaifuWbClient.getListUrl(ycfassetManagementUrl,urlDetailRegex);
			
//			List<HtmlAnchor> ycfobligationfundList=YicaifuWbClient.getListUrl(ycfobligationfundUrl,urlDetailRegex);
			
			//信托添加资管   产品列表
			trustList.addAll(assetManagementList);
			
//			trustList.addAll(ycfobligationfundList);
			
			//查询所有的正则  1财富
			Map<String, String> map=new HashMap<String, String>();
			map.put("webName", "1caifu");
			map.put("pageType", "trust");
			Map<String, String> trustMap = fpFetchProductRegexService.queryFetchXpath(map);
			map.put("pageType", "assetManagement");
			Map<String, String> assetManagementMap = fpFetchProductRegexService.queryFetchXpath(map);
			
			//获取详情
			for (HtmlAnchor htmlAnchor : trustList) {
				HtmlPage click=YicaifuWbClient.click(htmlAnchor);
				//获取产品的信息   信托
//				FpNewProductDTO initInfo = YicaifuWbClient.initInfo(click);   
				//20160612   壹财富 改版。更新   获取数据
//				FpNewProductDTO initInfo = YicaifuWbClient.initInfo20160612(click);
				//产品type
				String type=YicaifuWbClient.getText(click.getDocumentElement(), "//*[@id=\"tis\"]");
				FpNewProductDTO initInfo = null;
				if(type.contains("信托")){
					initInfo = YicaifuWbClient.initInfo20160713(click,trustMap);
				}else{//资管
					initInfo = YicaifuWbClient.initInfo20160713(click,assetManagementMap);
				}
				if(StringUtils.isBlank(initInfo.getpName())){
					log.error("getPName error"+click.getUrl().toString());
					continue;
				}
				try {
					//获取到产品信息 ，进行数据库保存。
					//根据  click.getUrl()  判断是否存在产品
					FpNewProductDTO fnProductDto=new FpNewProductDTO();
//					fnProductDto.setProductUrl(initInfo.getProductUrl());
					fnProductDto.setpName(initInfo.getpName());
					List<FpNewProductDTO> queryFpNewProductList = fpNewProductService.queryFpNewProductByWhere(fnProductDto);
					
					//数据存在进行数据更新操作
					if(queryFpNewProductList.size()>0){
						FpNewProductDTO oldProductInfo = queryFpNewProductList.get(0);
						//判断是否有数据更新
						String pRecruitmentSummary = oldProductInfo.getpRecruitmentSummary();
						String productAnnual = oldProductInfo.getProductAnnual();
						String pSaleStatus = oldProductInfo.getpSaleStatus();
						String url = oldProductInfo.getProductUrl();
						if(url.equals(initInfo.getProductUrl())&&pRecruitmentSummary.equals(initInfo.getpRecruitmentSummary())&&productAnnual.equals(initInfo.getProductAnnual())&&pSaleStatus.equals(initInfo.getpSaleStatus())){
							//无更新不作处理
						}else if(!"1".equals(oldProductInfo.getDeleteTag())){
							//已放弃的产品不更新
						}else{
							//进行更新
							StringBuffer oldInfo=new StringBuffer();
							oldInfo.append("P_RECRUITMENT_SUMMARY:").append(oldProductInfo.getpRecruitmentSummary());
							oldInfo.append("PRODUCT_ANNUAL:").append(oldProductInfo.getProductAnnual());
							oldInfo.append("P_SALE_STATUS:").append(oldProductInfo.getpSaleStatus());
							oldProductInfo.setOldInfo(oldInfo.toString());
							oldProductInfo.setpRecruitmentSummary(initInfo.getpRecruitmentSummary());
							oldProductInfo.setProductAnnual(initInfo.getProductAnnual());
							oldProductInfo.setpSaleStatus(initInfo.getpSaleStatus());
							oldProductInfo.setProductUrl(initInfo.getProductUrl());
							DTOdateSet.setUpdateInfo(oldProductInfo, null);
							oldProductInfo.setFlagUpdate("true");//有更新
							fpNewProductService.updateFpNewProduct(oldProductInfo);
						}
					}else{
						//设置为系统更新
						DTOdateSet.setCreateInfo(initInfo, null);
						DTOdateSet.setUpdateInfo(initInfo, null);
						initInfo.setProductSource("1caifu");
						initInfo.setFlagUpdate("true");
						//新产品  进行新增
						int fetchPId=fpNewProductService.addFpNewProduct(initInfo);
						
						ProjectDTO projectDto=new ProjectDTO();
						//判定是否需要建立关联关系  是否相同
						String name=initInfo.getpName();
						if(initInfo.getpType().contains("信托")){
							projectDto.setpType("02");
							if(!name.contains("信托")){
								name=name.replace("-", "信托-");
								//转化后 信托产品名称
								log.info("转化后 信托产品名称====="+name);
							}
						}else{
							projectDto.setpType("03");
						}
						projectDto.setpName(name);
						ProjectDTO searchProjectByName = projectDao.searchProjectByName(projectDto);
						if(searchProjectByName.getId()!=null&&searchProjectByName.getId()>0){
							//TODO 存在相同   绑定关系
 							log.info("存在相同产品。。。。"+searchProjectByName);
 							try {
								FpRelevanceDTO fpRelevanceDto=new FpRelevanceDTO();
								fpRelevanceDto.setpId(searchProjectByName.getId());
								fpRelevanceDto.setAssociationType("1");
								fpRelevanceDto.setFetchPId(fetchPId);
								fpRelevanceDto.setpType(projectDto.getpType());
								DTOdateSet.setCreateInfo(fpRelevanceDto, null);
								DTOdateSet.setUpdateInfo(fpRelevanceDto, null);
								fpRelevanceService.addFpRelevance(fpRelevanceDto);
							} catch (Exception e) {
								log.error("添加相同关系异常...",e);
							}
						}
					}
				} catch (Exception e) {
					//该页面进行产品转化出现问题
					log.error("current page in "+htmlAnchor.asXml());
					log.error("error 遍历 详情",e);
				}
			}
		} catch (Exception e) {
			log.error("error ycfproductInfojob",e);
			//通知    可能出现bug   壹财富拿不到数据
		}
		log.info("fetch end.....................");
	}
	
	
	
	
}
